package com.link.ppt.View;

import android.app.Dialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.caption.update.UpdateUtils;
import com.link.ppt.App.App;
import com.link.ppt.Base.BaseActivity;
import com.link.ppt.Consts.Constants;
import com.link.ppt.Model.Bean.BaseBean;
import com.link.ppt.Model.Bean.KeywordsBean;
import com.link.ppt.Model.Bean.PPTBean;
import com.link.ppt.Model.Bean.PPTEntity;
import com.link.ppt.Model.Bean.PersonalInfoBean;
import com.link.ppt.Model.IPPTModel;
import com.link.ppt.Model.IUserModel;
import com.link.ppt.Model.Impl.PPTModelImpl;
import com.link.ppt.Model.Impl.UserModelImpl;
import com.link.ppt.R;
import com.link.ppt.Utils.CommonSubscriber;
import com.link.ppt.Utils.DisplayUtil;
import com.link.ppt.Utils.GlideUtils;
import com.link.ppt.Utils.PreferenceUtils;
import com.link.ppt.Utils.ToastUtils;
import com.link.ppt.View.Adapter.PPTShareAdapter;
import com.link.ppt.Widget.LimitScrollerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action0;

public class MainActivity extends BaseActivity {

    @BindView(R.id.imv_user_info)
    CircleImageView imv_user_info;
    @BindView(R.id.edt_search_key)
    EditText edt_search_key;
    @BindView(R.id.swipe_refresh_layout)
    SmartRefreshLayout swipe_refresh_layout;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.floating_btn_publish)
    FloatingActionButton floating_btn_publish;
    @BindView(R.id.activity_main)
    CoordinatorLayout activity_main;
    @BindView(R.id.hotwords_limit)
    LimitScrollerView hotwords_limit;

    private List<PPTEntity> datas = new ArrayList<>();
    private PPTShareAdapter adapter;
    private List<String> scrollLimitList;
    private int page_index = 1;
    private boolean is_refresh = true;

    private View publish_ppt_view;
    private Dialog publish_ppt_dialog;
    RelativeLayout layout_method_1;
    RelativeLayout layout_method_2;
    ImageView imv_close_dialog;

    private View publish_ppt_url_view;
    private Dialog publish_ppt_dialog_url;
    private EditText edt_publish_url;
    private TextView tv_publish_url;
    private ImageView imv_close_dialog_publish;

    private LimitScrollerView.LimitScrollAdapter scrollAdapter;

    private IPPTModel pptModel;
    private IUserModel model;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        adapter = new PPTShareAdapter(this, datas);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
        recycler_view.setLayoutManager(manager);
        recycler_view.setAdapter(adapter);

        swipe_refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                is_refresh = true;
                swipe_refresh_layout.setEnableLoadmore(true);
                requestPPTStram();
            }
        });
        swipe_refresh_layout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                is_refresh = false;
                requestPPTStram();
            }
        });
        edt_search_key.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    is_refresh = true;
                    swipe_refresh_layout.setEnableLoadmore(true);
                    requestPPTStram();
                }
                return false;
            }
        });
        edt_search_key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    is_refresh = true;
                    swipe_refresh_layout.setEnableLoadmore(true);
                    requestPPTStram();
                }
            }
        });
        publish_ppt_view = View.inflate(MainActivity.this, R.layout.dialog_publish_ppt, null);
        publish_ppt_url_view = View.inflate(MainActivity.this, R.layout.dialog_publish_ppt_url, null);
        initDialoigViews();
        initDialogViewsUrl();
        initPublishDialog();
        initPublishUrlDialog();
        UpdateUtils.getInit().update(this, UpdateUtils.CHECK_AUTO);
        scrollLimitList = new ArrayList<>();
    }

    @Override
    public void setupData() {
        pptModel = new PPTModelImpl();
        model = new UserModelImpl();
        requestHotWords();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestPPTStram();
        if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
            imv_user_info.setImageResource(R.mipmap.unlogin);
        } else {
            model.RequestUserInfo().doOnSubscribe(new Action0() {
                @Override
                public void call() {
                }
            }).subscribe(new CommonSubscriber<PersonalInfoBean>() {
                @Override
                public void onSuccess(PersonalInfoBean info) {
                    GlideUtils.getInstance().loadSimpleContextVitMap(MainActivity.this, Constants.BASE_URL + info.getHeadImgUrl(), imv_user_info);
                }

                @Override
                public void onFailure(BaseBean response) {
                    ToastUtils.showShortToast(MainActivity.this, response.getDesc());
                }
            });
        }
    }


    private void requestHotWords() {
        pptModel.RequestHotKeywords().subscribe(new CommonSubscriber<KeywordsBean>() {
            @Override
            public void onSuccess(KeywordsBean response) {
                scrollLimitList.clear();
                if (response.getKeywords() != null && response.getKeywords().size() > 0) {
                    scrollLimitList.addAll(response.getKeywords());
                    hotwords_limit.setVisibility(View.VISIBLE);
                    initScrollAdapter(response);
                } else {
                    hotwords_limit.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                scrollLimitList.clear();
                hotwords_limit.setVisibility(View.GONE);
                ToastUtils.showShortToast(MainActivity.this, response.getDesc());
            }
        });
    }

    private void initScrollAdapter(final KeywordsBean response) {
        scrollAdapter = new LimitScrollerView.LimitScrollAdapter() {
            @Override
            public int getCount() {
                return response.getKeywords().size();
            }

            @Override
            public View getView(int index) {
                View itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.limit_scroller_item, null, false);
                TextView tv_text = (TextView) itemView.findViewById(R.id.tv_text);
                //绑定数据
                String data = scrollLimitList.get(index);
                itemView.setTag(data);
                tv_text.setText(data);
                return itemView;
            }
        };
        hotwords_limit.setDataAdapter(scrollAdapter);
        hotwords_limit.startScroll();
        hotwords_limit.setOnItemClickListener(new LimitScrollerView.OnItemClickListener() {
            @Override
            public void onItemClick(Object obj) {
                String hotwords = (String) obj;
                is_refresh = true;
                swipe_refresh_layout.setEnableLoadmore(true);
                edt_search_key.setText(hotwords);
                requestPPTStram();
            }
        });
    }

    private void requestPPTStram() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }
        pptModel.RequestPPTStream(edt_search_key.getText().toString(), local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
            }
        }).subscribe(new CommonSubscriber<PPTBean>() {
            @Override
            public void onSuccess(PPTBean response) {
//                hideProgress();
                swipe_refresh_layout.finishRefresh();
                swipe_refresh_layout.finishLoadmore();
                if ((response.getDataList() != null) && (response.getDataList().size() > 0)) {
                    if (is_refresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    datas.addAll(response.getDataList());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                    page_index++;
                } else {
                    swipe_refresh_layout.finishLoadmore();
                    swipe_refresh_layout.setEnableLoadmore(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                swipe_refresh_layout.finishRefresh();
                ToastUtils.showShortToast(MainActivity.this, response.getDesc());
            }
        });
    }

    private void initDialoigViews() {
        layout_method_1 = (RelativeLayout) publish_ppt_view.findViewById(R.id.layout_method_1);
        layout_method_2 = (RelativeLayout) publish_ppt_view.findViewById(R.id.layout_method_2);
        imv_close_dialog = (ImageView) publish_ppt_view.findViewById(R.id.imv_close_dialog);
        imv_close_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publish_ppt_dialog.dismiss();
            }
        });
        layout_method_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publish_ppt_dialog_url.show();
                publish_ppt_dialog.dismiss();
            }
        });
        layout_method_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publish_ppt_dialog.dismiss();
                Intent intent = new Intent(MainActivity.this, SelectPhotoActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this).title("提示").content("是否确定退出?").positiveText("确定").negativeText("取消").cancelable(false).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    App.GetInstance().finishActivity();
                }
            }).build();
            dialog.show();
        } else {
            return super.onKeyDown(keyCode, event);
        }
        return true;
    }


    private void initDialogViewsUrl() {
        edt_publish_url = (EditText) publish_ppt_url_view.findViewById(R.id.edt_publish_url);
        tv_publish_url = (TextView) publish_ppt_url_view.findViewById(R.id.tv_publish_url);
        imv_close_dialog_publish = (ImageView) publish_ppt_url_view.findViewById(R.id.imv_close_dialog_publish);
        imv_close_dialog_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edt_publish_url.setText("");
                publish_ppt_dialog_url.dismiss();
            }
        });
        tv_publish_url.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edt_publish_url.getText().toString())) {
                    ToastUtils.showShortToast(MainActivity.this, R.string.ppt_string_44);
                    return;
                }
                if (!TextUtils.isEmpty(edt_publish_url.getText().toString())) {
                    if ((!edt_publish_url.getText().toString().contains("http")) && (!edt_publish_url.getText().toString().contains("https")) && (!edt_publish_url.getText().toString().contains("HTTP")) && (!edt_publish_url.getText().toString().contains("HTTPS"))) {
                        ToastUtils.showShortToast(MainActivity.this, R.string.ppt_string_44);
                        return;
                    }
                    publishPPTURL(edt_publish_url.getText().toString());
                }
            }
        });
    }

    private void initPublishDialog() {
        publish_ppt_dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = publish_ppt_dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(MainActivity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        publish_ppt_dialog.setCancelable(false);
        publish_ppt_dialog.setContentView(publish_ppt_view);
    }


    private void initPublishUrlDialog() {
        publish_ppt_dialog_url = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = publish_ppt_dialog_url.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(MainActivity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        publish_ppt_dialog_url.setCancelable(false);
        publish_ppt_dialog_url.setContentView(publish_ppt_url_view);
    }

    @OnClick({R.id.imv_user_info, R.id.floating_btn_publish})
    void doClicks(View view) {
        if (TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        } else {
            int id = view.getId();
            switch (id) {
                case R.id.imv_user_info:
                    if (!TextUtils.isEmpty(PreferenceUtils.GetUserToken())) {
                        Intent intent = new Intent(MainActivity.this, PersonalInfoActivity.class);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                    break;
                case R.id.floating_btn_publish:
                    publish_ppt_dialog.show();
                    break;
            }
        }
    }

    private void publishPPTURL(String url) {
        pptModel.PublishPPTUrl(url).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                is_refresh = true;
                requestPPTStram();
                edt_publish_url.setText("");
                publish_ppt_dialog_url.dismiss();
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.showShortToast(MainActivity.this, response.getDesc());
            }
        });
    }
}
